extends CharacterBody2D

## 新增：导入 PlayerStats 脚本
const PlayerStats = preload("res://scripts/player/player_stats.gd")

const SPEED = 200 #速度
const JUMP_VELOCITY = -300.0 #跳跃力度
const DOUBLE_JUMP_VELOCITY = -300.0 #二段跳力度
const LAND_THRESHOLD = 1000.0 #着陆动画速度临界点
const ATTACK_DAMAGE = 50.0 #攻击伤害
const ATTACK_COOLDOWN = 0 #攻击冷却时间
const INVINCIBLE_TIME = 2.0 #无敌时间
const ATTACK_COMBO_RESET_TIME = 1.0 #连击数重置计数器
# 原先的最大生命值常量已在 PlayerStats 中管理，可注释掉此行
# const MAX_HEALTH = 100  # 添加最大生命值常量
const DAMAGE_COUNT_RESET_TIME = 1.0  # 1.0秒内的连续受击
const DAMAGE_COUNT_THRESHOLD = 3  # 3次连续受击触发无敌
const KNOCKBACK_DURATION = 0.2  # 增加击退持续时间
const KNOCKBACK_FORCE = 150.0   # 增加水平击退力
const KNOCKBACK_UP_FORCE = -150.0  # 增加向上的力
const KNOCKBACK_FRICTION = 800.0   # 增加摩擦力
# 疾风斩相关常量
const QUICK_SLASH_SPEED = 500.0 # 疾风斩冲锋速度
const QUICK_SLASH_DURATION = 0.3 # 疾风斩持续时间
const QUICK_SLASH_COOLDOWN = 2.0 # 疾风斩冷却时间

# 贴墙滑动相关常量
const WALL_SLIDE_SPEED = 50.0 # 贴墙滑动速度
const WALL_JUMP_VELOCITY = Vector2(-250, -250) # 墙跳的速度和方向

@onready var animated_sprite = $AnimatedSprite2D
@onready var attack_range = $AttackRange 
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
var has_double_jump = true

# 新增：使用 PlayerStats 来管理玩家属性
var stats : PlayerStats

# 为了让其它脚本通过 player.health 取得当前健康值，新增只读属性 health
var health: int:
	get:
		return stats.current_health

var is_hurt = false
var is_dead = false
var was_in_air = false
var knockback_direction = Vector2.ZERO
var knockback_duration = 0.3
var knockback_timer: float = 0.0
var just_jumped = false
var previous_y_velocity = 0.0
var is_landing = false
var is_attacking = false
var can_attack = true
var is_invincible = false

# 贴墙滑动相关变量
var is_wall_sliding = false
var wall_direction = 0

# 移除原有的计时器初始化
var sword_wave_timer: Timer
var sword_wave_cooldown: Timer
# 新增剑气波相关变量
var is_sword_wave_active = false
var sword_wave_damage_multiplier = 0.5  # 剑气伤害为普通攻击的50%

# 新增疾风斩相关变量
var quick_slash_timer: Timer
var quick_slash_cooldown: Timer
var is_quick_slashing = false
var quick_slash_damage_multiplier = 1.2  # 疾风斩伤害为普通攻击的120%

var attack_combo_index = 0
var last_attack_time = 0.0
var is_in_dialog = false
var sword_master_talking = false  # 已存在于现有代码中
var damage_count = 0
var damage_reset_timer = null
var is_in_knockback: bool = false
var current_item_effect: Node2D = null
var current_weapon_effect: Node2D = null  # 新增武器特效专用变量
var level_up_effect_scene = preload("res://scenes/level_up_effect.tscn")
var skill_tree_scene = preload("res://scenes/skill_tree.tscn")
var skill_tree_instance = null
var skill_tree_visible = false  # 改名为skill_tree_visible

# 已命中敌人记录 - 防止疾风斩多次伤害同一敌人
var _hit_enemies = []

func _ready():
	print("玩家节点初始化...")
	add_to_group("player")
	print("玩家已加入 'player' 组")
	
	# 初始化玩家属性
	stats = PlayerStats.new()
	add_child(stats)
	stats.level_up_effect.connect(_on_level_up_effect)
	print("玩家stats初始化完成：等级 ", stats.level, "，已学习技能：", stats.skills)
	
	# 确保基础技能已学习
	if not stats.has_skill("basic_swing"):
		stats.skills.append("basic_swing")
		print("自动学习基础技能：basic_swing")
	
	# 测试：提升玩家等级到3级，方便测试技能学习
	while stats.level < 3:
		stats.add_exp(stats.exp_to_next)
		print("测试：提升玩家等级到", stats.level)
	
	animated_sprite.animation_finished.connect(_on_animation_finished)
	
	# 等待一帧确保所有节点都准备好
	sword_wave_timer = Timer.new()
	sword_wave_timer.one_shot = true
	sword_wave_timer.wait_time = stats.sword_wave_duration
	sword_wave_timer.timeout.connect(_on_sword_wave_timeout)
	add_child(sword_wave_timer)
	
	sword_wave_cooldown = Timer.new()
	sword_wave_cooldown.one_shot = true
	sword_wave_cooldown.wait_time = stats.sword_wave_cooldown_time
	sword_wave_cooldown.timeout.connect(_on_sword_wave_cooldown_timeout)
	add_child(sword_wave_cooldown)
	
	# 初始化疾风斩技能计时器
	quick_slash_timer = Timer.new()
	quick_slash_timer.one_shot = true
	quick_slash_timer.wait_time = stats.quick_slash_duration
	# 注意：这里不再连接timeout信号，因为在perform_quick_slash函数中使用await
	add_child(quick_slash_timer)
	
	quick_slash_cooldown = Timer.new()
	quick_slash_cooldown.one_shot = true
	quick_slash_cooldown.wait_time = stats.quick_slash_cooldown_time
	quick_slash_cooldown.timeout.connect(_on_quick_slash_cooldown_timeout)
	add_child(quick_slash_cooldown)
	
	# 添加剑气波效果指示器
	var sword_wave_indicator = ColorRect.new()
	sword_wave_indicator.name = "SwordWaveIndicator"
	sword_wave_indicator.color = Color(0.2, 0.5, 1.0, 0.3)
	sword_wave_indicator.size = Vector2(30, 30)
	sword_wave_indicator.position = Vector2(-15, -50)
	sword_wave_indicator.visible = false
	add_child(sword_wave_indicator)
	
	var sword_master = get_tree().get_first_node_in_group("sword_master")
	if sword_master:
		print("找到剑士，连接对话信号")  # 调试信息
		sword_master.dialog_started.connect(_on_dialog_started)
		sword_master.dialog_ended.connect(_on_dialog_ended)
		# 连接新的对话信号
		sword_master.phase_two_dialog_started.connect(_on_phase_two_dialog_started)
		sword_master.phase_two_dialog_ended.connect(_on_phase_two_dialog_ended)
	else:
		print("未找到剑士")  # 调试信息
	
	# 确保玩家节点层级
	self.z_index = 0
	
	print("玩家初始金币数量:", stats.coins if stats.has_property("coins") else "未定义")

func _physics_process(delta):
	# 如果技能树打开，禁用所有操作
	if skill_tree_visible:
		velocity.x = 0
		velocity.y += gravity * delta
		move_and_slide()
		return
	
	# 如果在对话中，优先处理对话状态
	if is_in_dialog:
		# 只有在普通对话中才停止移动，剑士二阶段对话允许移动
		if !sword_master_talking:
			velocity.x = 0  # 确保停止水平移动
		else:
			# 在剑士二阶段对话中允许移动和跳跃
			var direction = Input.get_axis("move_left", "move_right")
			if direction:
				velocity.x = direction * SPEED
				if is_on_floor() and !is_attacking and !is_hurt and !is_landing:
					animated_sprite.play("run")
					animated_sprite.flip_h = direction < 0
					if attack_range:
						attack_range.scale.x = -1 if direction < 0 else 1
			else:
				velocity.x = move_toward(velocity.x, 0, SPEED)
				if is_on_floor() and !is_attacking and !is_hurt and !is_landing:
					animated_sprite.play("idle")
			
			# 处理二阶段对话中的跳跃
			if Input.is_action_just_pressed("jump") and is_on_floor():
				velocity.y = JUMP_VELOCITY
				animated_sprite.play("jump")
				was_in_air = true
		
		velocity.y += gravity * delta  # 应用正常重力
		move_and_slide()
		
		# 如果正在播放其他动画，等待动画完成，但允许fall动画过渡到idle
		if animated_sprite.animation in ["attack1", "attack2", "attack3", "hurt", "jump"]:
			return
		
		# 特殊处理fall动画：如果在地面上，强制切换到idle
		if animated_sprite.animation == "fall" and is_on_floor():
			animated_sprite.play("idle")
			return
		
		# 如果刚刚落地
		if is_on_floor() and was_in_air:
			was_in_air = false
			if previous_y_velocity > LAND_THRESHOLD:
				is_landing = true
				animated_sprite.play("land")
			else:
				if sword_master_talking and velocity.x != 0:
					animated_sprite.play("run")
				else:
					animated_sprite.play("idle")
		else:
			# 如果在空中，继续播放fall动画
			if !is_on_floor() and velocity.y > 0 and !is_attacking and !is_hurt:
				animated_sprite.play("fall")
			elif !sword_master_talking or velocity.x == 0:
				if is_on_floor():
					animated_sprite.play("idle")
		return
	
	# 在现有代码前添加特效位置更新
	if current_weapon_effect:
		update_weapon_effect_position()
	
	# 修改击退处理
	if is_in_knockback:
		knockback_timer -= delta
		if knockback_timer <= 0:
			is_in_knockback = false
			knockback_timer = 0
			velocity = Vector2.ZERO  # 确保完全停止
		else:
			# 在击退过程中仍然应用重力
			velocity.y += gravity * delta * 0.5  # 减小重力影响
			# 应用水平摩擦力
			velocity.x = move_toward(velocity.x, 0, KNOCKBACK_FRICTION * delta)
			move_and_slide()
			return
	
	# 如果正在执行疾风斩，优先处理疾风斩逻辑
	if is_quick_slashing:
		# 应用正常重力
		velocity.y += gravity * delta
		move_and_slide()
		
		# 检查是否击中敌人
		check_attack_hit()
		return
	
	# 确保每帧都重置攻击输入状态
	can_attack = true
	
	# 如果死亡、在对话中或剑士正在说话，只应用重力和移动，但不允许水平移动
	if is_dead or is_in_dialog:  # 移除 sword_master_talking 检查
		velocity.x = 0  # 确保停止水平移动
		velocity.y += gravity * delta  # 保持重力效果
		move_and_slide()
		return
	
	# 处理移动
	var direction = Input.get_axis("move_left", "move_right")
	if direction:
		velocity.x = direction * SPEED
		if is_on_floor() and not is_attacking and not is_hurt:
			animated_sprite.play("run")
		animated_sprite.flip_h = direction < 0
		if attack_range:
			attack_range.scale.x = -1 if direction < 0 else 1
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		if is_on_floor() and not is_attacking and not is_landing and not is_hurt:
			animated_sprite.play("idle")
	
	# 处理贴墙滑动
	wall_direction = 0
	if is_on_wall_only() and not is_on_floor():
		var collision = get_last_slide_collision()
		if collision:
			wall_direction = -1 if collision.get_normal().x > 0 else 1
	
	# 如果在空中靠近墙壁时按Z键，启动贴墙滑动
	if wall_direction != 0 and Input.is_action_pressed("primary_skill") and not is_on_floor() and not is_attacking and not is_hurt:
		is_wall_sliding = true
		velocity.y = WALL_SLIDE_SPEED
		animated_sprite.play("wallslide")
		animated_sprite.flip_h = wall_direction < 0 # 修正为角色面向墙壁
	else:
		is_wall_sliding = false
	
	# 处理跳跃
	if Input.is_action_just_pressed("jump"):
		if is_on_floor():
			velocity.y = JUMP_VELOCITY
		elif is_wall_sliding: # 墙跳
			velocity.x = WALL_JUMP_VELOCITY.x * wall_direction
			velocity.y = WALL_JUMP_VELOCITY.y
			animated_sprite.play("jump")
			is_wall_sliding = false
	
	# 添加重力 (如果不是在贴墙滑动)
	if not is_on_floor() and not is_wall_sliding:
		velocity.y += gravity * delta
		was_in_air = true
		if not is_dead and not is_hurt and not is_attacking:
			if velocity.y < 0:
				animated_sprite.play("jump")
			else:
				animated_sprite.play("fall")
	elif was_in_air and not is_wall_sliding:
		was_in_air = false
		if not is_dead and not is_attacking and not is_hurt:
			if previous_y_velocity > LAND_THRESHOLD:
				is_landing = true
				animated_sprite.play("land")
			elif is_in_dialog:
				animated_sprite.play("idle")
		previous_y_velocity = 0.0
	
	# 更新移动
	move_and_slide()
	
	# 处理攻击输入
	if Input.is_action_just_pressed("mouse_left") and can_attack and not is_attacking and not is_hurt and not is_wall_sliding:
		perform_attack()
	
	# 记录当前帧的Y速度用于下一帧判断是否需要播放落地动画
	previous_y_velocity = velocity.y

func perform_attack():
	if is_dead or is_in_dialog or skill_tree_visible:  # 添加技能树检查
		return
		
	is_attacking = true
	can_attack = false
	just_jumped = false
	# 如果超过组合攻击重置时间，则从第一段攻击开始
	if Time.get_unix_time_from_system() - last_attack_time > ATTACK_COMBO_RESET_TIME:
		attack_combo_index = 0
	last_attack_time = Time.get_unix_time_from_system()
	var attack_anims = ["attack1", "attack2", "attack3"]
	animated_sprite.play(attack_anims[attack_combo_index])
	# 更新组合攻击序号，如果已经是最后一段攻击则下次重置为第一段
	if attack_combo_index < attack_anims.size() - 1:
		attack_combo_index += 1
	else:
		attack_combo_index = 0
	if attack_range:
		attack_range.scale.x = -1 if animated_sprite.flip_h else 1

	# 如果剑气波处于激活状态，在攻击时生成剑气波
	if is_sword_wave_active:
		spawn_sword_wave()
		print("释放剑气波！")

func _on_animation_finished():
	if animated_sprite.animation == "land":
		is_landing = false
		if is_in_dialog:
			animated_sprite.play("idle")
		else:
			# 根据当前状态决定下一个动画
			if velocity.x != 0:
				animated_sprite.play("run")
			else:
				animated_sprite.play("idle")
	elif animated_sprite.animation == "hurt":
		is_hurt = false
		if is_in_dialog:
			animated_sprite.play("idle")
	elif animated_sprite.animation in ["attack1", "attack2", "attack3"]:
		is_attacking = false
		
		# 检查是否击中敌人
		print("检查攻击范围内的敌人...")
		var enemies_in_range = attack_range.get_overlapping_bodies()
		print("攻击范围内有", enemies_in_range.size(), "个物体")
		
		for body in enemies_in_range:
			print("发现碰撞体：", body.name, "，组：", body.get_groups())
			if body.is_in_group("enemy"):
				print("发现敌人，准备造成伤害")
				if body.has_method("take_damage"):
					body.take_damage(ATTACK_DAMAGE, global_position)
					print("击中敌人，造成伤害：", ATTACK_DAMAGE)
				else:
					print("警告：敌人没有take_damage方法")
		# 攻击冷却
		await get_tree().create_timer(ATTACK_COOLDOWN).timeout
		can_attack = true
		if not is_dead and not is_in_dialog:  # 检查玩家是否死亡或在对话中
			animated_sprite.play("idle")
	elif animated_sprite.animation == "death":
		print("死亡动画播放完成")
		# 等待一小段时间
		await get_tree().create_timer(0.5).timeout
		# 淡出效果
		var tween = create_tween()
		tween.tween_property(animated_sprite, "modulate:a", 0.0, 1.0)
		await tween.finished
		# 重新开始游戏或返回主菜单
		get_tree().change_scene_to_file("res://scenes/main_menu.tscn")

func take_damage(amount: float, attacker_position: Vector2 = Vector2.ZERO):
	if is_dead or is_invincible or is_in_dialog:
		return
	
	stats.current_health -= amount
	print("玩家受到伤害：", amount, " 当前生命值：", stats.current_health)
	
	if stats.current_health <= 0:
		die()
		return
	
	# 受伤状态和动画处理
	is_hurt = true
	is_attacking = false
	can_attack = false
	animated_sprite.play("hurt")
	
	# 计算击退方向和力度
	var dir = (global_position - attacker_position).normalized()
	
	# 应用击退，但限制最大速度
	velocity.x = dir.x * KNOCKBACK_FORCE
	velocity.y = KNOCKBACK_UP_FORCE  # 固定向上的力
	
	# 启动击退状态
	is_in_knockback = true
	knockback_timer = KNOCKBACK_DURATION
	
	# 增加伤害计数
	damage_count += 1
	
	# 重置之前的计时器（如果存在）
	if damage_reset_timer and damage_reset_timer.time_left > 0:
		damage_reset_timer.timeout.disconnect(_reset_damage_count)
	
	# 创建新的计时器
	damage_reset_timer = get_tree().create_timer(DAMAGE_COUNT_RESET_TIME)
	damage_reset_timer.timeout.connect(_reset_damage_count)
	
	# 处理连击无敌
	if damage_count >= DAMAGE_COUNT_THRESHOLD:
		is_invincible = true
		var tween = create_tween()
		for i in range(4):
			tween.tween_property(animated_sprite, "modulate:a", 0.2, 0.2)
			tween.tween_property(animated_sprite, "modulate:a", 1.0, 0.2)
		
		await get_tree().create_timer(INVINCIBLE_TIME).timeout
		is_invincible = false
		damage_count = 0
	
	# 等待受伤动画完成
	await animated_sprite.animation_finished
	is_hurt = false
	can_attack = true

func die():
	if is_dead:
		return
		
	is_dead = true
	is_hurt = false
	is_attacking = false  # 确保停止所有状态
	is_in_knockback = false
	velocity.x = 0  # 只停止水平移动，保持垂直移动（重力）
	
	# 禁用碰撞
	set_collision_layer_value(1, false)
	set_collision_mask_value(3, false)
	
	# 确保从第一帧开始播放死亡动画
	animated_sprite.stop()  # 停止当前动画
	animated_sprite.frame = 0  # 重置到第一帧
	animated_sprite.play("death")  # 播放死亡动画
	
	# 等待动画播放完成
	if not animated_sprite.animation_finished.is_connected(_on_animation_finished):
		animated_sprite.animation_finished.connect(_on_animation_finished)
	
	# 创建一个循环来处理死亡时的物理效果，直到动画完成
	while not animated_sprite.animation == "death" or animated_sprite.frame < animated_sprite.sprite_frames.get_frame_count("death") - 1:
		velocity.y += gravity * get_physics_process_delta_time()
		move_and_slide()
		await get_tree().physics_frame

func _on_dialog_started():
	print("对话开始")
	is_in_dialog = true
	velocity.x = 0  # 只停止水平移动
	
	# 如果在地面上，直接播放站立动画
	if is_on_floor():
		animated_sprite.play("idle")

func _on_dialog_ended():
	print("对话结束")  # 调试信息
	is_in_dialog = false
	# 确保重置攻击相关状态
	is_attacking = false
	can_attack = true

func _on_phase_two_dialog_started():
	is_in_dialog = true
	sword_master_talking = true

func _on_phase_two_dialog_ended():
	print("二阶段对话结束")
	print("对话状态：", is_in_dialog)
	print("剑士对话状态：", sword_master_talking)
	print("攻击状态：", is_attacking)
	print("可攻击状态：", can_attack)
	
	# 先重置状态
	is_in_dialog = false
	sword_master_talking = false
	
	# 确保可以立即攻击和跳跃
	is_attacking = false
	can_attack = true
	is_invincible = false  # 确保不会处于无敌状态
	is_hurt = false  # 确保不会处于受伤状态
	is_in_knockback = false  # 确保不会处于击退状态
	
	# 如果玩家在地面上，播放idle动画
	if is_on_floor():
		animated_sprite.play("idle")
	else:
		# 如果在空中，根据垂直速度播放相应动画
		if velocity.y < 0:
			animated_sprite.play("jump")
		else:
			animated_sprite.play("fall")
		
	# 添加一个小延迟，确保状态完全重置
	await get_tree().create_timer(0.1).timeout
	print("状态重置完成，现在可以攻击和跳跃")

# 添加重置伤害计数的函数
func _reset_damage_count():
	if not is_invincible:  # 只在非无敌状态下重置计数
		damage_count = 0
		print("重置连击计数")

func _input(event):
	if is_dead:
		return
	
	# 在普通对话中禁用所有输入，但在剑士二阶段对话中允许移动和跳跃
	if is_in_dialog and !sword_master_talking:
		return
	
	# 处理技能面板的打开和关闭
	if event.is_action_pressed("ui_skill"):  # 使用G键(ui_skill)
		if skill_tree_visible:
			close_skill_tree()
		else:
			open_skill_tree()
		return
	
	# 如果技能树打开，禁用其他输入
	if skill_tree_visible:
		return
	
	# 处理攻击输入
	if event.is_action_pressed("mouse_left") and can_attack and !is_attacking and !is_hurt:
		perform_attack()
		
	# 新增Q键检测 - 只在非对话状态下可用
	if !is_in_dialog and event.is_action_pressed("skill_q"):
		if stats.has_method("has_skill") and stats.has_skill("sword_wave") and sword_wave_cooldown.time_left == 0:
			activate_sword_wave()
			
	# 新增R键检测 - 疾风斩
	if !is_in_dialog and event.is_action_pressed("skill_r"):
		if stats.has_method("has_skill") and stats.has_skill("quick_slash") and quick_slash_cooldown.time_left == 0 and !is_quick_slashing and !is_attacking and !is_hurt:
			perform_quick_slash()

# 检查技能树是否打开
func is_skill_tree_open() -> bool:
	return get_tree().get_nodes_in_group("skill_tree").size() > 0

# 关闭技能树
func close_skill_tree():
	if skill_tree_visible:
		skill_tree_visible = false
		if skill_tree_instance:
			skill_tree_instance.queue_free()
			skill_tree_instance = null
		print("技能树已关闭")
		can_attack = true  # 恢复攻击状态

# 添加获取玩家stats的方法，供其他脚本调用
func get_stats():
	if stats:
		print("Player.get_stats被调用，返回stats对象")
		return stats
	else:
		print("警告：Player.get_stats被调用，但stats未初始化")
		return null

func show_item_effect(item_texture: Texture2D, is_weapon: bool = false):
	if is_weapon:
		print("--- 开始装备武器特效 ---")  # 新增调试语句
		if current_weapon_effect:
			print("发现已有武器特效，正在移除...")
			current_weapon_effect.queue_free()
			current_weapon_effect = null
		
		print("创建新武器特效节点")
		# 使用新的武器特效场景
		var weapon_effect_scene = load("res://scenes/effects/weapon_effect.tscn")
		if weapon_effect_scene:
			current_weapon_effect = weapon_effect_scene.instantiate()
			
			# 获取物品数据库
			var item_db = get_node_or_null("/root/ItemDatabase")
			var weapon_name = ""
			
			# 尝试从资源路径获取武器名称
			if item_texture and item_texture.resource_path:
				var texture_name = item_texture.resource_path.get_file().get_basename()
				print("纹理名称: ", texture_name)
				
				# 检查是否为裁星者
				if texture_name == "ColorfulSword_idle" or texture_name == "ColorfulSword":
					weapon_name = "裁星者"
					print("识别为裁星者武器")
			
			# 根据玩家朝向设置初始位置
			var x_offset = 20 if animated_sprite.flip_h else -20  # 根据朝向调整
			current_weapon_effect.position = Vector2(x_offset, -30)  # 背后上方位置
			print("初始位置：", current_weapon_effect.position, " 玩家朝向: ", "左" if animated_sprite.flip_h else "右")
			
			# 设置层级
			current_weapon_effect.z_index = -100  # 使用更大的负值
			current_weapon_effect.z_as_relative = false
			
			# 添加到玩家节点
			add_child(current_weapon_effect)
			move_child(current_weapon_effect, 0)  # 移动到子节点列表最前
			
			# 设置武器名称 - 延迟调用
			if current_weapon_effect.has_method("set_weapon"):
				print("设置武器名称: ", weapon_name)
				# 等待一帧后再设置武器名称
				await get_tree().process_frame
				if current_weapon_effect and is_instance_valid(current_weapon_effect):
					current_weapon_effect.set_weapon(weapon_name)
		else:
			print("错误：无法加载武器特效场景")
		
		return
	
	# 处理消耗品特效（原有逻辑）
	if current_item_effect:
		current_item_effect.queue_free()
	
	current_item_effect = Node2D.new()
	var sprite = Sprite2D.new()
	sprite.texture = item_texture
	sprite.scale = Vector2(0.8, 0.8)
	
	add_child(current_item_effect)
	current_item_effect.add_child(sprite)
	
	var x_offset = 50
	if animated_sprite.flip_h:
		x_offset = -x_offset
	
	current_item_effect.position = Vector2(x_offset, 0)
	current_item_effect.z_index = -1  # 确保在玩家背后
	
	var tween = create_tween().set_loops()
	tween.tween_property(current_item_effect, "position:y", -20, 1.5).set_ease(Tween.EASE_IN_OUT)
	tween.tween_property(current_item_effect, "position:y", 0, 1.5).set_ease(Tween.EASE_IN_OUT)
	
	await get_tree().create_timer(5.0).timeout
	if is_instance_valid(current_item_effect):
		current_item_effect.queue_free()

func update_weapon_effect_position():
	if not current_weapon_effect:
		return
		
	# 根据玩家朝向调整武器位置
	var x_offset = 20  # 基础偏移量
	
	# 如果玩家面向左侧，武器应该在左侧背后
	# 如果玩家面向右侧，武器应该在右侧背后
	if animated_sprite.flip_h:
		# 玩家面向左侧
		x_offset = x_offset  # 正值，在左侧
	else:
		# 玩家面向右侧
		x_offset = -x_offset  # 负值，在右侧
	
	# 更新武器位置，只修改水平位置，保持垂直位置由浮动动画控制
	current_weapon_effect.position.x = x_offset
	
	# 调试输出
	print("更新武器位置: x=", x_offset, " 玩家朝向: ", "左" if animated_sprite.flip_h else "右")

func _on_level_up_effect(pos: Vector2):
	var effect = level_up_effect_scene.instantiate()
	effect.position = Vector2(0, -50)  # 在玩家头顶上方显示
	add_child(effect)
	
	# 创建闪光效果
	var tween = create_tween()
	for i in range(2):  # 闪烁两次
		tween.tween_property(animated_sprite, "modulate", Color(2, 2, 2), 0.2)  # 变亮
		tween.tween_property(animated_sprite, "modulate", Color(1, 1, 1), 0.2)  # 恢复

func activate_sword_wave():
	print("剑气波激活！")
	is_sword_wave_active = true
	sword_wave_timer.start()
	sword_wave_cooldown.start()
	
	# 显示剑气波激活指示器
	var indicator = get_node_or_null("SwordWaveIndicator")
	if indicator:
		indicator.visible = true
		
		# 添加闪烁动画
		var tween = create_tween()
		tween.tween_property(indicator, "modulate", Color(1, 1, 1, 0.7), 0.5)
		tween.tween_property(indicator, "modulate", Color(1, 1, 1, 1.0), 0.5)
		tween.set_loops()
	
	# 播放激活音效和特效
	play_sword_wave_activation_effect()

func _on_sword_wave_timeout():
	# 剑气波持续时间结束
	is_sword_wave_active = false
	
	# 隐藏指示器
	var indicator = get_node_or_null("SwordWaveIndicator")
	if indicator:
		indicator.visible = false
	
	print("剑气波效果已结束")

func _on_sword_wave_cooldown_timeout():
	print("剑气波技能冷却完毕，可以再次使用")

func spawn_sword_wave():
	# 创建剑气波实例
	var sword_wave = preload("res://scenes/sword_wave.tscn").instantiate()
	
	# 设置剑气波属性
	sword_wave.damage = ATTACK_DAMAGE * sword_wave_damage_multiplier
	sword_wave.direction = Vector2.RIGHT if !animated_sprite.flip_h else Vector2.LEFT
	
	# 设置剑气波位置（从玩家前方生成，位置适中）
	var offset_x = 30 * (1 if !animated_sprite.flip_h else -1)
	sword_wave.global_position = global_position + Vector2(offset_x, -15)  # 将Y轴偏移从-30改为-15，使其位置更合理
	
	# 添加到场景
	get_parent().add_child(sword_wave)
	
	# 确保剑气波能正确造成伤害
	sword_wave.set_collision_layer_value(4, true)  # 设置为第4层，确保能与敌人碰撞
	sword_wave.set_collision_mask_value(2, true)   # 设置碰撞掩码为第2层，检测敌人
	
	# 剑气波生成特效
	create_sword_wave_spawn_effect(sword_wave.global_position)
	
	print("生成剑气波，伤害值：", sword_wave.damage, "，位置：", sword_wave.global_position)
	print("剑气波碰撞层：", sword_wave.get_collision_layer(), "，碰撞掩码：", sword_wave.get_collision_mask())

# 创建剑气波生成特效
func create_sword_wave_spawn_effect(spawn_position):
	# 创建一个特效节点
	var effect = Node2D.new()
	effect.global_position = spawn_position
	get_parent().add_child(effect)
	
	# 创建冲击波特效
	var wave_ring = Line2D.new()
	wave_ring.width = 3.0
	wave_ring.default_color = Color(0.3, 0.7, 1.0, 0.7)
	
	# 创建圆形点
	var circle_points = []
	var radius = 15.0
	var segments = 12
	for i in range(segments + 1):
		var angle = i * 2 * PI / segments
		var point = Vector2(cos(angle) * radius, sin(angle) * radius)
		circle_points.append(point)
	
	wave_ring.points = circle_points
	effect.add_child(wave_ring)
	
	# 添加粒子爆发
	var particles = CPUParticles2D.new()
	particles.amount = 20
	particles.lifetime = 0.4
	particles.explosiveness = 0.8
	particles.direction = Vector2(1 if animated_sprite.flip_h else -1, 0)
	particles.spread = 30
	particles.gravity = Vector2.ZERO
	particles.initial_velocity_min = 50
	particles.initial_velocity_max = 150
	particles.scale_amount_min = 1.0
	particles.scale_amount_max = 3.0
	
	# 添加粒子大小和颜色变化
	particles.scale_amount_curve = Curve.new()
	particles.scale_amount_curve.add_point(Vector2(0, 1.0))
	particles.scale_amount_curve.add_point(Vector2(0.7, 0.7))
	particles.scale_amount_curve.add_point(Vector2(1.0, 0.0))
	
	particles.color_ramp = Gradient.new()
	particles.color_ramp.add_point(0.0, Color(0.9, 0.95, 1.0, 0.9))
	particles.color_ramp.add_point(0.5, Color(0.4, 0.7, 1.0, 0.6))
	particles.color_ramp.add_point(1.0, Color(0.3, 0.5, 0.8, 0.0))
	
	particles.emitting = true
	particles.one_shot = true
	effect.add_child(particles)
	
	# 创建动画
	var tween = create_tween()
	tween.tween_property(wave_ring, "width", 0.5, 0.3)
	tween.parallel().tween_property(wave_ring, "modulate", Color(0.3, 0.7, 1.0, 0.0), 0.3)
	tween.parallel().tween_property(wave_ring, "scale", Vector2(2.0, 2.0), 0.3)
	
	# 自动清理
	await get_tree().create_timer(0.5).timeout
	if is_instance_valid(effect):
		effect.queue_free()

func play_sword_wave_activation_effect():
	# 创建激活特效
	var activation_effect = Node2D.new()
	activation_effect.name = "SwordWaveActivationEffect"
	add_child(activation_effect)
	
	# 创建环形波纹特效
	var ring = Line2D.new()
	ring.width = 3.0
	ring.default_color = Color(0.3, 0.7, 1.0, 0.7)
	
	# 创建圆形点
	var circle_points = []
	var radius = 25.0
	var segments = 16
	for i in range(segments + 1):
		var angle = i * 2 * PI / segments
		var point = Vector2(cos(angle) * radius, sin(angle) * radius)
		circle_points.append(point)
	
	ring.points = circle_points
	activation_effect.add_child(ring)
	
	# 发光效果
	var light = PointLight2D.new()
	var light_texture = GradientTexture2D.new()
	var light_gradient = Gradient.new()
	light_gradient.add_point(0, Color(1, 1, 1, 1))
	light_gradient.add_point(1, Color(0.3, 0.7, 1.0, 0))
	light_texture.gradient = light_gradient
	light_texture.width = 128
	light_texture.height = 128
	light_texture.fill = GradientTexture2D.FILL_RADIAL
	light_texture.fill_from = Vector2(0.5, 0.5)
	light_texture.fill_to = Vector2(1, 0.5)
	
	light.texture = light_texture
	light.color = Color(0.3, 0.7, 1.0, 0.8)
	light.energy = 1.0
	light.texture_scale = 1.0
	activation_effect.add_child(light)
	
	# 创建粒子效果 - 向外扩散的蓝色粒子
	var particles = CPUParticles2D.new()
	particles.position = Vector2(0, -30)
	particles.amount = 30
	particles.lifetime = 0.6
	particles.explosiveness = 0.8
	particles.direction = Vector2(0, -1)
	particles.spread = 180
	particles.gravity = Vector2(0, 20)  # 轻微向下的引力
	particles.initial_velocity_min = 50
	particles.initial_velocity_max = 150
	particles.scale_amount_min = 1.0
	particles.scale_amount_max = 3.0
	
	# 添加粒子大小和颜色变化
	particles.scale_amount_curve = Curve.new()
	particles.scale_amount_curve.add_point(Vector2(0, 1.0))
	particles.scale_amount_curve.add_point(Vector2(0.7, 0.7))
	particles.scale_amount_curve.add_point(Vector2(1.0, 0.0))
	
	particles.color_ramp = Gradient.new()
	particles.color_ramp.add_point(0.0, Color(0.9, 0.95, 1.0, 0.9))
	particles.color_ramp.add_point(0.5, Color(0.4, 0.7, 1.0, 0.6))
	particles.color_ramp.add_point(1.0, Color(0.3, 0.5, 0.8, 0.0))
	
	particles.emitting = true
	particles.one_shot = true
	activation_effect.add_child(particles)
	
	# 添加剑气能量积蓄线效果
	var energy_lines = Node2D.new()
	energy_lines.name = "EnergyLines"
	activation_effect.add_child(energy_lines)
	
	# 创建8条从中心向外的能量线
	for i in range(8):
		var line = Line2D.new()
		line.default_color = Color(0.9, 0.95, 1.0, 0.8)
		line.width = 1.5
		
		var angle = i * PI / 4
		var length = 40.0
		var points = [
			Vector2(0, 0),
			Vector2(cos(angle) * length, sin(angle) * length)
		]
		line.points = points
		energy_lines.add_child(line)
	
	# 创建动画效果
	var tween = create_tween()
	
	# 环形波纹扩散
	tween.tween_property(ring, "width", 1.0, 0.4)
	tween.parallel().tween_property(ring, "scale", Vector2(1.5, 1.5), 0.4)
	tween.parallel().tween_property(ring, "modulate", Color(0.3, 0.7, 1.0, 0.0), 0.4)
	
	# 光效闪烁
	tween.parallel().tween_property(light, "energy", 1.5, 0.2)
	tween.parallel().tween_property(light, "energy", 0.6, 0.3)
	
	# 等待动画完成
	await tween.finished
	
	# 创建第二个波纹
	var ring2 = Line2D.new()
	ring2.width = 2.0
	ring2.default_color = Color(0.3, 0.7, 1.0, 0.5)
	ring2.points = circle_points
	activation_effect.add_child(ring2)
	
	var tween2 = create_tween()
	tween2.tween_property(ring2, "width", 0.5, 0.3)
	tween2.parallel().tween_property(ring2, "scale", Vector2(2.0, 2.0), 0.3)
	tween2.parallel().tween_property(ring2, "modulate", Color(0.3, 0.7, 1.0, 0.0), 0.3)
	
	# 播放音效 - 使用更加锐利的剑气声音
	var audio_player = AudioStreamPlayer.new()
	var sound = AudioStreamGenerator.new()
	sound.mix_rate = 44100
	sound.buffer_length = 0.2
	
	audio_player.stream = sound
	audio_player.volume_db = -8
	audio_player.pitch_scale = 1.2
	add_child(audio_player)
	audio_player.play()
	
	# 添加第二个音效，增强切割感
	var audio_player2 = AudioStreamPlayer.new()
	var sound2 = AudioStreamGenerator.new()
	sound2.mix_rate = 44100
	sound2.buffer_length = 0.1
	
	audio_player2.stream = sound2
	audio_player2.volume_db = -15
	audio_player2.pitch_scale = 1.9
	add_child(audio_player2)
	audio_player2.play()
	
	# 自动清理
	await get_tree().create_timer(0.8).timeout
	audio_player.queue_free()
	audio_player2.queue_free()
	
	# 清理特效
	if is_instance_valid(activation_effect):
		activation_effect.queue_free()

# 新增：带名称参数的武器特效显示函数
func show_item_effect_with_name(item_texture: Texture2D, item_name: String):
	print("--- 开始装备武器特效（带名称）---")
	print("物品名称: ", item_name)
	
	if current_weapon_effect:
		print("发现已有武器特效，正在移除...")
		current_weapon_effect.queue_free()
		current_weapon_effect = null
	
	print("创建新武器特效节点")
	# 使用新的武器特效场景
	var weapon_effect_scene = load("res://scenes/effects/weapon_effect.tscn")
	if weapon_effect_scene:
		current_weapon_effect = weapon_effect_scene.instantiate()
		
		# 根据玩家朝向设置初始位置
		var x_offset = 20 if animated_sprite.flip_h else -20  # 根据朝向调整
		current_weapon_effect.position = Vector2(x_offset, -30)  # 背后上方位置
		print("初始位置：", current_weapon_effect.position, " 玩家朝向: ", "左" if animated_sprite.flip_h else "右")
		
		# 设置层级
		current_weapon_effect.z_index = -100  # 使用更大的负值
		current_weapon_effect.z_as_relative = false
		
		# 添加到玩家节点
		add_child(current_weapon_effect)
		move_child(current_weapon_effect, 0)  # 移动到子节点列表最前
		
		# 设置武器名称 - 延迟调用
		if current_weapon_effect.has_method("set_weapon"):
			print("设置武器名称: ", item_name)
			# 等待一帧后再设置武器名称
			await get_tree().process_frame
			if current_weapon_effect and is_instance_valid(current_weapon_effect):
				current_weapon_effect.set_weapon(item_name)
	else:
		print("错误：无法加载武器特效场景")

func open_skill_tree():
	if not skill_tree_visible:
		skill_tree_visible = true
		skill_tree_instance = skill_tree_scene.instantiate()
		add_child(skill_tree_instance)
		print("技能树已打开")

# 添加收集金币的方法
func add_coins(amount: int):
	if stats.has_property("coins"):
		stats.coins += amount
		print("收集到", amount, "个金币，当前总数:", stats.coins)
	else:
		print("警告：玩家stats中没有coins属性")

# 新增：执行疾风斩
func perform_quick_slash():
	print("疾风斩激活！")
	is_quick_slashing = true
	is_attacking = true
	can_attack = false
	
	# 进入无敌状态
	is_invincible = true
	
	# 添加无敌状态视觉效果
	var tween = create_tween()
	tween.tween_property(animated_sprite, "modulate", Color(1.5, 1.5, 2.0, 0.8), 0.1)
	
	# 保存原始碰撞设置
	var original_collision_mask = get_collision_mask()
	var original_collision_layer = get_collision_layer()
	
	# 修改碰撞掩码，完全禁用与敌人碰撞 (第3层是敌人)
	set_collision_mask_value(3, false)
	# 修改碰撞层，避免敌人检测到玩家
	set_collision_layer_value(1, false)
	
	# 播放攻击动画1
	animated_sprite.play("attack1")
	
	# 设置冲刺方向和速度
	var direction = 1.0 if !animated_sprite.flip_h else -1.0
	velocity.x = direction * QUICK_SLASH_SPEED
	
	# 播放特效
	play_quick_slash_effect()
	
	# 开始计时
	quick_slash_timer.start()
	quick_slash_cooldown.start()
	
	# 确保疾风斩状态在整个持续时间内检测碰撞
	var damage_check_timer = Timer.new()
	damage_check_timer.wait_time = 0.05 # 每0.05秒检测一次
	damage_check_timer.autostart = true
	add_child(damage_check_timer)
	
	# 连接定时检测敌人函数
	damage_check_timer.timeout.connect(func():
		check_attack_hit()
	)
	
	# 疾风斩结束后恢复碰撞和无敌状态
	await quick_slash_timer.timeout
	
	# 恢复原始碰撞设置
	set_collision_mask(original_collision_mask)
	set_collision_layer(original_collision_layer)
	
	# 关闭无敌状态
	is_invincible = false
	is_quick_slashing = false
	is_attacking = false
	can_attack = true
	
	# 恢复正常外观
	tween = create_tween()
	tween.tween_property(animated_sprite, "modulate", Color(1, 1, 1, 1), 0.2)
	
	# 清理计时器
	damage_check_timer.queue_free()
	
	# 如果玩家在地面上，播放idle动画
	if is_on_floor():
		animated_sprite.play("idle")
	
	print("疾风斩效果结束")

# 播放疾风斩特效
func play_quick_slash_effect():
	# 创建冲刺轨迹特效
	var particles = CPUParticles2D.new()
	particles.name = "QuickSlashParticles"
	particles.position = Vector2(0, 0)  # 修改为角色中心位置
	particles.z_index = -1  # 设置为-1确保在玩家后面
	particles.amount = 60  # 增加粒子数量
	particles.lifetime = 0.8  # 增加粒子存活时间
	particles.local_coords = false
	particles.explosiveness = 0.0
	particles.spread = 10
	particles.direction = Vector2(1 if animated_sprite.flip_h else -1, 0)
	particles.initial_velocity_min = 0
	particles.initial_velocity_max = 15  # 降低最大速度，让粒子留存更久
	particles.scale_amount_min = 3.0
	particles.scale_amount_max = 4.0
	
	# 添加粒子大小变化曲线，使它们逐渐缩小
	particles.scale_amount_curve = Curve.new()
	particles.scale_amount_curve.add_point(Vector2(0, 1.0))
	particles.scale_amount_curve.add_point(Vector2(0.7, 0.8))
	particles.scale_amount_curve.add_point(Vector2(1.0, 0.0))
	
	# 添加粒子透明度变化曲线，使它们逐渐消失
	particles.color_ramp = Gradient.new()
	particles.color_ramp.add_point(0.0, Color(0.7, 0.8, 1.0, 0.8))
	particles.color_ramp.add_point(0.6, Color(0.7, 0.8, 1.0, 0.7))
	particles.color_ramp.add_point(1.0, Color(0.7, 0.8, 1.0, 0.0))
	
	particles.emitting = true
	particles.one_shot = false
	add_child(particles)
	
	# 添加拖尾效果
	var trail = Line2D.new()
	trail.name = "QuickSlashTrail"
	trail.width = 15.0
	trail.default_color = Color(0.7, 0.8, 1.0, 0.6)
	trail.z_index = -1  # 确保在玩家后面
	add_child(trail)
	
	# 添加额外的速度线特效
	var speed_lines = CPUParticles2D.new()
	speed_lines.name = "SpeedLines"
	speed_lines.position = Vector2(0, 0)  # 修改为角色中心位置
	speed_lines.z_index = -1  # 设置为-1确保在玩家后面
	speed_lines.amount = 40  # 增加粒子数量
	speed_lines.lifetime = 0.4  # 增加粒子存活时间
	speed_lines.explosiveness = 0.2
	speed_lines.direction = Vector2(1 if animated_sprite.flip_h else -1, 0)
	speed_lines.spread = 30
	speed_lines.gravity = Vector2.ZERO
	speed_lines.initial_velocity_min = 100
	speed_lines.initial_velocity_max = 200
	speed_lines.scale_amount_min = 10.0
	speed_lines.scale_amount_max = 20.0
	
	# 调整速度线的消失曲线
	speed_lines.scale_amount_curve = Curve.new()
	speed_lines.scale_amount_curve.add_point(Vector2(0, 1))
	speed_lines.scale_amount_curve.add_point(Vector2(0.7, 0.7))
	speed_lines.scale_amount_curve.add_point(Vector2(1, 0))
	
	# 调整速度线的透明度
	speed_lines.color_ramp = Gradient.new()
	speed_lines.color_ramp.add_point(0.0, Color(0.9, 0.95, 1.0, 0.4))
	speed_lines.color_ramp.add_point(0.7, Color(0.9, 0.95, 1.0, 0.2))
	speed_lines.color_ramp.add_point(1.0, Color(0.9, 0.95, 1.0, 0.0))
	
	speed_lines.emitting = true
	add_child(speed_lines)
	
	# 持续更新拖尾位置
	var trail_timer = Timer.new()
	trail_timer.wait_time = 0.01  # 更高频率更新，更流畅
	trail_timer.autostart = true
	add_child(trail_timer)
	
	trail_timer.timeout.connect(func():
		trail.add_point(global_position)
		# 限制点数量
		if trail.get_point_count() > 15:  # 增加点数量，拖尾更长
			trail.remove_point(0)
	)
	
	# 自动清理特效 - 在技能结束时只停止发射新粒子
	await quick_slash_timer.timeout
	particles.emitting = false
	speed_lines.emitting = false
	trail_timer.queue_free()
	
	# 等待所有粒子自然消失
	await get_tree().create_timer(0.8).timeout  # 增加等待时间，让粒子自然消失
	
	# 淡出拖尾
	var tween = create_tween()
	tween.tween_property(trail, "modulate:a", 0.0, 0.7)  # 增加淡出时间
	await tween.finished
	
	# 清理特效
	particles.queue_free()
	speed_lines.queue_free()
	trail.queue_free()

# 获取剑气波冷却百分比（0.0表示可用，1.0表示完全冷却中）
func get_sword_wave_cooldown_percent() -> float:
	if !sword_wave_cooldown || !stats:
		return 0.0
	
	if sword_wave_cooldown.time_left <= 0:
		return 0.0
	
	# 确保我们有一个有效的冷却时间基值
	var cooldown_time = stats.sword_wave_cooldown_time
	if cooldown_time <= 0:
		cooldown_time = 10.0  # 默认值
	
	return min(sword_wave_cooldown.time_left / cooldown_time, 1.0)

# 获取疾风斩冷却百分比（0.0表示可用，1.0表示完全冷却中）
func get_quick_slash_cooldown_percent() -> float:
	if !quick_slash_cooldown || !stats:
		return 0.0
	
	if quick_slash_cooldown.time_left <= 0:
		return 0.0
	
	# 确保我们有一个有效的冷却时间基值
	var cooldown_time = stats.quick_slash_cooldown_time
	if cooldown_time <= 0:
		cooldown_time = 2.0  # 默认值
	
	return min(quick_slash_cooldown.time_left / cooldown_time, 1.0)

# 检查攻击是否击中敌人
func check_attack_hit():
	var enemies_in_range = attack_range.get_overlapping_bodies()
	for body in enemies_in_range:
		if body.is_in_group("enemy"):
			if body.has_method("take_damage"):
				var damage = ATTACK_DAMAGE
				
				# 如果是疾风斩，增加伤害和击退效果
				if is_quick_slashing:
					damage *= quick_slash_damage_multiplier
					# 增加疾风斩的命中判定
					print("疾风斩击中敌人：", body.name)
				
				# 检查这个敌人是否已经被当前的疾风斩攻击过
				if is_quick_slashing and _has_hit_enemy(body):
					# 已经命中过这个敌人，跳过
					continue
				
				# 记录已经命中的敌人（仅疾风斩时）
				if is_quick_slashing:
					_add_hit_enemy(body)
				
				# 向敌人传递额外标记，通知这是疾风斩伤害
				body.take_damage(damage, global_position, is_quick_slashing)
				print("攻击击中敌人，造成伤害：", damage)

# 添加已命中敌人到记录
func _add_hit_enemy(enemy):
	if not enemy in _hit_enemies:
		_hit_enemies.append(enemy)
		# 创建一个延迟清理，确保下次疾风斩可以再次命中
		get_tree().create_timer(quick_slash_cooldown.wait_time * 0.5).timeout.connect(func():
			if enemy in _hit_enemies:
				_hit_enemies.erase(enemy)
		)

# 检查敌人是否已被命中
func _has_hit_enemy(enemy):
	return enemy in _hit_enemies

# 处理疾风斩冷却完毕
func _on_quick_slash_cooldown_timeout():
	print("疾风斩技能冷却完毕，可以再次使用")

# 简单的判断是否为玩家的函数，供其他脚本调用
func is_player() -> bool:
	return true
